package com.hc.wdj.auth.server.data.resolver;

import com.hc.wdj.auth.server.constant.OAuthConstants;
import com.hc.wdj.auth.server.data.model.request.ClientIdAndSecretModel;
import com.hc.wdj.auth.server.error.OAuthError;
import com.hc.wdj.core.context.model.HcRequest;
import com.hc.wdj.core.exception.HcException;
import com.hc.wdj.core.httpauth.basic.HttpBasicUtil;
import org.apache.commons.lang3.StringUtils;

/**
 * @author ryanwdj
 * @since 2024/11/19
 */
public class OAuthDataResolverDefaultImpl implements OAuthDataResolver{


    /**
     * 从请求对象中获取
     * @param request
     * @return
     */
    @Override
    public ClientIdAndSecretModel readClientIdAndSecret(HcRequest request) {
        // 优先从请求参数中获取
        String clientId = request.getParam(OAuthConstants.Param.client_id);
        String clientSecret = request.getParam(OAuthConstants.Param.client_secret);
        if(StringUtils.isNotEmpty(clientId)){
            return new ClientIdAndSecretModel(clientId, clientSecret);
        }
        // 如果请求参数中没有提供client_id， 则尝试从Authorization中获取
        String authorizationValue = HttpBasicUtil.getAuthorizationValue();
        if(StringUtils.isNotEmpty(authorizationValue)){
            String[] arr = authorizationValue.split(":");
            clientId = arr[0];
            if(arr.length>1){
                clientSecret = arr[1];
            }
            return new ClientIdAndSecretModel(clientId, clientSecret);
        }
        // 如果都没有，则抛出异常
        throw new HcException(OAuthError.MISSING_CLIENT_INFO);
    }
}
